package com.ccx.coachsite.util;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Toast;

import com.ccx.coachsite.util.weibo.sina.CommonUtils;
import com.ccx.coachsite.util.weibo.sina.StringUtils;
import com.ccx.coachsite.util.weibo.sina.WeiboUtils;
import com.weibo.net.AccessToken;
import com.weibo.net.DialogError;
import com.weibo.net.Oauth2AccessTokenHeader;
import com.weibo.net.Utility;
import com.weibo.net.Weibo;
import com.weibo.net.WeiboDialogListener;
import com.weibo.net.WeiboException;

public class OpenShareSinaWeiBo {

	private Context mContext;
	private ProgressDialog dialog;
	private SharedPreferences data;
	private String shareAppName;
	private String mUserId;
	public OpenShareSinaWeiBo(Context context){
		mContext = context;
		
		dialog = new ProgressDialog(mContext);
		dialog.setIndeterminate(false);
		dialog.setCancelable(true);
		
		data = mContext.getSharedPreferences(CommonUtils.WEIBO, 0);
	}
	
	
	public void shareSinaWeiBo( String targetPackage, String appName, String userId){
		shareAppName = appName;
		mUserId = userId;
		String localToken = data.getString("localToken_"+mUserId, "");
		long localExpiresIn = data.getLong("localExpiresIn_"+mUserId, 0);

		boolean isSessionValid = WeiboUtils.isSessionValid(localToken, localExpiresIn);
		//本地Token是否已经过期
		if (isSessionValid) {
			Utility.setAuthorization(new Oauth2AccessTokenHeader());
			AccessToken accessToken = new AccessToken(localToken, "459c43b7c458877a42faf63f27716c35");
			accessToken.setExpiresIn(localExpiresIn);
			
			Weibo.getInstance().setAccessToken(accessToken);

			dialog.setMessage(OpenShareTool.getShareDesc(mContext)+"中...");
			dialog.show();
			UpdateStatusThread ust = new UpdateStatusThread();
			new Thread(ust).start();
		} else {
			Weibo weibo = Weibo.getInstance();
			weibo.setupConsumerConfig("2310674465","12061ad3bba0642fd8e13a7d06c0500d");
			weibo.setRedirectUrl("http://117.27.144.30/3g/callback/sina");
			weibo.authorize((Activity)mContext, new AuthDialogListener());
		}
	}
	
	public class AuthDialogListener implements WeiboDialogListener {

		@Override
		public void onComplete(Bundle values) {
			String token = values.getString("access_token");
			String expires_in = values.getString("expires_in");
			String uid = values.getString("uid");

			long localExpiresIn = System.currentTimeMillis()
					+ Integer.parseInt(expires_in) * 1000;
			
			WeiboUtils.updateLocalToken(mUserId,data, uid, token, localExpiresIn);
			
			AccessToken accessToken = new AccessToken(token, Weibo.getAppSecret());
			accessToken.setExpiresIn(expires_in);
			Weibo.getInstance().setAccessToken(accessToken);

			dialog.setMessage(OpenShareTool.getShareDesc(mContext)+"中...");
			dialog.show();
			new Thread(new UpdateStatusThread()).start();
		}
		
		@Override
		public void onError(DialogError e) {
			Toast.makeText(mContext,
					"Auth error : " + e.getMessage(), Toast.LENGTH_LONG).show();
		}

		@Override
		public void onCancel() {
			Toast.makeText(mContext, "Auth cancel",
					Toast.LENGTH_LONG).show();
		}

		@Override
		public void onWeiboException(WeiboException e) {
			Toast.makeText(mContext,
					"Auth exception : " + e.getMessage(), Toast.LENGTH_LONG)
					.show();
		}
	}
	
	//微博分享线程
	public class UpdateStatusThread implements Runnable {	
		
		public void run() {

			int retCode = 0;
			String retMsg = "";

			Weibo weibo = Weibo.getInstance();

			try {
				retMsg = WeiboUtils.update(mContext, weibo, "2310674465", shareAppName, "", "");
				retCode = 1;
			} catch (WeiboException e) {
				retCode = -1;
				retMsg = e.getMessage();
			} catch (Exception e) {
				retCode = -1;
				retMsg = e.getMessage();
			}
			
			Message msg = new Message();
			Bundle data = new Bundle();
			data.putInt("retCode", retCode);
			data.putString("retMsg", retMsg);
			msg.setData(data);
			
			shareHandler.sendMessage(msg);
		}
	}
		
	Handler shareHandler = new Handler() {
		
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			dialog.hide();

			Bundle data = msg.getData();
			int retCode = data.getInt("retCode");
			String retMsg = data.getString("retMsg");

			if (retCode == 1) {
				Toast.makeText(mContext, OpenShareTool.getShareDesc(mContext)+"成功。", Toast.LENGTH_SHORT).show();				
			} else {
				if (StringUtils.isBlank(retMsg)) {
					Toast.makeText(mContext, OpenShareTool.getShareDesc(mContext)+"失败。", Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(mContext, OpenShareTool.getShareDesc(mContext)+"失败，" + retMsg,Toast.LENGTH_SHORT).show();
				}
			}
		}
	};
}
